package com.chushouya.order.util;

import com.general.framework.core.lang.Lists;
import com.chushouya.order.constants.ClerkOrderActionEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dto.api.clerk.action.ClerkOrderAction;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ClerkOrderActionUtil {

    /**
     * 业务员订单各状态下，可执行的操作列表
     */
    private static Map<Integer, List<ClerkOrderAction>> clerkOrderActionMap = Maps.newHashMap();

    private ClerkOrderActionUtil() {}

    @PostConstruct
    public void initClerkOrderAction() {
//        log.debug("----------业务员订单操作----------");
        Lists.asList(OrderStatusEnum.values()).forEach(orderStatus->{
//            log.debug("订单状态:{},{}", orderStatus.value(), orderStatus.named());
            final List<ClerkOrderAction> actionList = getActionList(orderStatus);
            if (Lists.isNotEmpty(actionList)) {
                clerkOrderActionMap.put(orderStatus.value(), actionList);
            }
//            log.debug("-----------------------------");
        });
    }

    private static List<ClerkOrderAction> getActionList(OrderStatusEnum orderStatus) {
        List<ClerkOrderAction> optionList = Lists.newArrayList();
        Lists.asList(ClerkOrderActionEnum.values()).forEach(actionEnum -> {
            // 如果moreCondition为true时，是否有该操作的权限需在xxxCtrl逻辑里面控制
            if (actionEnum.fromOrderStatus().contains(orderStatus) && !actionEnum.moreCondition()) {
                optionList.add(new ClerkOrderAction(actionEnum.getActionCode(), actionEnum.getActionName(), actionEnum.getActionText(), actionEnum.getActionType()));
//                log.debug("   操作:{},{}", actionEnum.getActionCode(), actionEnum.getActionName());
            }
        });
        return optionList;
    }

    public static List<ClerkOrderAction> clerkOrderActions(Integer orderStatus) {
        final List<ClerkOrderAction> currentStatusActions = clerkOrderActionMap.get(orderStatus);
        if (Lists.isEmpty(currentStatusActions)) {
            return Lists.newArrayList();
        }
        return new ArrayList<>(currentStatusActions);
    }
}
